import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
}

export const useMealStore = defineStore(
  'meal',
  () => {
    // 从本地存储加载数据
    const loadFromStorage = () => {
      try {
        // 检查是否在浏览器环境
        if (typeof uni !== 'undefined' && uni.getStorageSync) {
          const stored = uni.getStorageSync('meal-store')
          if (stored) {
            try {
              const data = JSON.parse(stored)
              // 验证数据结构
              if (Array.isArray(data.mealList) && Array.isArray(data.waterList)) {
                return {
                  meals: data.mealList,
                  waterRecords: data.waterList
                }
              }
            } catch (e) {
              console.error('解析存储数据失败:', e)
            }
          }
        }
      } catch (e) {
        console.error('加载记录失败:', e)
      }
      return { meals: [], waterRecords: [] }
    }

    // 加载初始数据
    const { meals, waterRecords } = loadFromStorage()
    
    // 定义响应式数据
    const mealList = ref([...meals]) // 确保创建新数组触发响应式
    const waterList = ref([...waterRecords]) // 确保创建新数组触发响应式

    // 监听变化，自动保存到本地存储
    watch(
      () => ({ mealList: [...mealList.value], waterList: [...waterList.value] }),
      (newData) => {
        try {
          if (typeof uni !== 'undefined' && uni.setStorageSync) {
            uni.setStorageSync('meal-store', JSON.stringify(newData))
          }
        } catch (e) {
          console.error('保存记录失败:', e)
        }
      },
      { deep: true, immediate: true } // 立即执行一次保存初始化数据
    )

    // 获取今日日期
    const getToday = () => new Date().toISOString().split('T')[0]

    // 今日饮食记录
    const todayMeals = computed(() => {
      const today = getToday()
      return mealList.value.filter(meal => meal.date === today)
    })

    // 今日饮水记录
    const todayWater = computed(() => {
      const today = getToday()
      return waterList.value.filter(record => record.date === today)
    })

    // 今日摄入总热量
    const todayTotalHeat = computed(() => {
      return todayMeals.value.reduce((total, meal) => total + (meal.heat || 0), 0)
    })

    // 今日总饮水量
    const todayTotalWater = computed(() => {
      return todayWater.value.reduce((total, record) => total + (record.amount || 0), 0)
    })

    // 添加饮食记录
    const addMeal = (meal) => {
      const newMeal = {
        id: generateId(),
        date: getToday(),
        time: new Date().toTimeString().slice(0, 5),
        ...meal
      }
      mealList.value.push(newMeal)
      return newMeal
    }

    // 删除饮食记录
    const removeMeal = (mealId) => {
      mealList.value = mealList.value.filter(meal => meal.id !== mealId)
    }

    // 添加饮水记录
    const addWater = (amount) => {
      const newRecord = {
        id: generateId(),
        date: getToday(),
        time: new Date().toTimeString().slice(0, 5),
        amount: parseInt(amount) || 0
      }
      waterList.value.push(newRecord)
      return newRecord
    }

    // 删除饮水记录
    const removeWater = (recordId) => {
      waterList.value = waterList.value.filter(record => record.id !== recordId)
    }

    // 清空今日记录
    const clearTodayRecords = () => {
      const today = getToday()
      mealList.value = mealList.value.filter(meal => meal.date !== today)
      waterList.value = waterList.value.filter(record => record.date !== today)
    }

    return {
      mealList,
      waterList,
      todayMeals,
      todayWater,
      todayTotalHeat,
      todayTotalWater,
      addMeal,
      removeMeal,
      addWater,
      removeWater,
      clearTodayRecords
    }
  }
)
